package com.mdc.mansion.common.util.http;

import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.mdc.mansion.common.mapper.JsonMapper;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * http的工具类
 * @author chenmingdong
 * 2016年1月28日
 *
 */
public class HttpToolKit {
	/**
	 * 发送get请求获取数据
	 * @param uri
	 * @return
	 * @throws Exception
	 */
	public static String get(String uri) throws Exception{
		return get(uri,null);
	}
	/**
	 * 发送get请求获取数据
	 * @param uri 请求的URL地址
	 * @param mp 请求中参数
	 * @return
	 * @throws Exception
	 */
	public static String get(String uri,Map<String, String> mp) throws Exception{
		HttpGet httpGet=new HttpGet(uri);
	    if(mp!=null){
	    	final Set<String> keys = mp.keySet();
		    uri+="?";
		    for(String key:keys){
		    	String v=mp.get(key);
		    	uri+=key+"="+v+"&";
		    }
		    uri=uri.substring(0, uri.length()-1);
	    }
	    return httpExecute(httpGet);
	}
	/**
	 * 发送post获取数据
	 * @param uri
	 * @param mp
	 * @return
	 * @throws Exception
	 */
	public static String post(String uri,Map<String, String> mp) throws Exception{
		HttpPost httpPost=new HttpPost(uri);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		final Set<String> keySet = mp.keySet();
		for(String key:keySet){
			nvps.add(new BasicNameValuePair(key, mp.get(key)));
		}
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
		return httpExecute(httpPost);
	}
	public static String postJson(String uri,Map<String, String> mp) throws Exception{
		HttpPost httpPost=new HttpPost(uri);
		String json = JsonMapper.toJson(mp);
		StringEntity se = new StringEntity(json);
		se.setContentEncoding("UTF-8");  
        se.setContentType("application/json");//发送json需要设置contentType  
		httpPost.setEntity(se);
		return httpExecute(httpPost);
	}
	/**
	 * 开始网络通信获取数据
	 * @param httpRequest
	 * @return
	 * @throws Exception
	 * @throws IOException
	 */
	private static String httpExecute(HttpRequestBase httpRequest) throws Exception,IOException {
		String ret=null;
		CloseableHttpClient closeableHttpClient=HttpClients.createDefault();
		CloseableHttpResponse response=null;
		try {
			response = closeableHttpClient.execute(httpRequest);
			ret=EntityUtils.toString(response.getEntity(), "utf-8");
		}catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			if(response!=null)
				response.close();
		}
		return ret;
	}
	
	
	  public static String postSSL(String url, Map<String, String> params) {  
	        CloseableHttpClient httpClient = null;  
	        HttpPost httpPost = null;  
	        String result = "";  
	        try {  
	            httpClient = (CloseableHttpClient) wrapClient();  
	            RequestConfig requestConfig = RequestConfig.custom()  
	                    .setSocketTimeout(4000).setConnectTimeout(4000).build();  
	            httpPost = new HttpPost(url);  
	            httpPost.setConfig(requestConfig);  
	            List<NameValuePair> ps = new ArrayList<NameValuePair>();  
	            for (String pKey : params.keySet()) {  
	                ps.add(new BasicNameValuePair(pKey, params.get(pKey)));  
	            }  
	            httpPost.setEntity(new UrlEncodedFormEntity(ps, "utf-8"));  
	            CloseableHttpResponse response = httpClient.execute(httpPost);  
	            HttpEntity httpEntity = response.getEntity();  
	  
	            result = EntityUtils.toString(httpEntity, "utf-8");  
	  
	        } catch (ClientProtocolException e) {  
	            result = "";  
	        } catch (IOException e) {  
	            result = "";  
	        } finally {  
	            try {  
	                if (httpPost != null) {  
	                    httpPost.releaseConnection();  
	                }  
	                if (httpClient != null) {  
	                    httpClient.close();  
	                }  
	            } catch (IOException e) {  
	                result = "";  
	            }  
	        }  
	        return result;  
	    }  
	    
	    private static HttpClient wrapClient() {  
	        try {  
	            SSLContext ctx = SSLContext.getInstance("TLS");  
	            X509TrustManager tm = new X509TrustManager() {  
	                public X509Certificate[] getAcceptedIssuers() {  
	                    return null;  
	                }  
	  
	                public void checkClientTrusted(X509Certificate[] arg0,  
	                        String arg1) throws CertificateException {  
	                }  
	  
	                public void checkServerTrusted(X509Certificate[] arg0,  
	                        String arg1) throws CertificateException {  
	                }  
	            };  
	            ctx.init(null, new TrustManager[] { tm }, null);  
	            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(  
	                    ctx, NoopHostnameVerifier.INSTANCE);  
	            CloseableHttpClient httpclient = HttpClients.custom()  
	                    .setSSLSocketFactory(ssf).build();  
	            return httpclient;  
	        } catch (Exception e) {  
	            return HttpClients.createDefault();  
	        }  
	    }  
}
